package com.springboot.news.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.springboot.news.mapper.ArticleMapper;
import com.springboot.news.domain.po.Article;
import com.springboot.news.domain.po.PageBean;
import com.springboot.news.service.ArticleService;
import com.springboot.news.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize,Integer categoryId,String status) {
//        创建pagebean对象
        PageBean<Article> pb = new PageBean<>();
//      开启分页查询pagehelper
        PageHelper.startPage(pageNum, pageSize);
//调用mapper
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as = articleMapper.list(userId, categoryId, status);
//        page中提供了方法,可以获取pagehelper分页查询后,得到的总记录条数和当前页数据
        Page<Article> p = (Page<Article>) as;
//        把数据填充到pagebean对象中
        pb.setTotal(p.getTotal());
        pb.setList(p.getResult());
        return pb;
    }
    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleMapper.add(article);
    }
    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
    @Override
    public Article detail(Integer id) {
        return articleMapper.detail(id);
    }
    @Override
    public void update(Article article) {   article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);

        articleMapper.update(article);
    }
}
